/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package company.general;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import system.general.Exc;
import system.general.Logged;
import system.general.Message;
import system.general.Persistencia;

/**
 *
 * @author emojica
 */
@ManagedBean(name = "company_general")
@ViewScoped
public class Main extends Beans {

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Message msg = new Message();
    private Find company_generalFind = new Find();
    private List<Beans> company_generalList = new ArrayList<>();
    private String sql;
    private Map<String, String> map = new LinkedHashMap<>();

    public Main() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
        load();
    }

    private void load() {
        try {
            map.clear();
            if (logged.getMasterId() == 0) {
                map.put("com.id = " + logged.getDetailId(), " ");
            } else {
                map.put("com.id = " + logged.getMasterId(), " ");
            }


            company_generalList.clear();
            company_generalList = company_generalFind.byMap(map);

            if (!company_generalList.isEmpty()) {
                setNombre(company_generalList.get(0).getNombre());
                setDireccion(company_generalList.get(0).getDireccion());
                setTelefono(company_generalList.get(0).getTelefono());
                setContacto(company_generalList.get(0).getContacto());
                logged.setMasterName(this.getNombre());
            }

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void insert() {
        try {

            //Verifica si el registro existe, de lo contrario lo inserta
            map.clear();
            map.put("nombre = '" + getNombre(), "'");
            if (company_generalFind.byExist(map)) {
                throw new Exc("m5");
            }

            sql = "INSERT INTO public.compania (nombre, direccion, telefono, contacto) "
                    + "VALUES ('" + getNombre() + "',"
                    + "'" + getDireccion() + "',"
                    + "'" + getTelefono() + "',"
                    + "'" + getContacto() + "')";


            //Inserta la información del registro
            persistencia.executeUpdate(sql);


            //Localiza el id del registro recien insertado, con la llave única
            map.clear();
            company_generalList.clear();
            map.put("com.nombre = '" + getNombre(), "' ");
            company_generalList = company_generalFind.byMap(map);
            //Asigna el id del registro insertado a la variable global del formulario
            logged.setMasterId(company_generalList.get(0).getId());

            throw new Exc("m1");
        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void update() {
        try {

            
            if (logged.getMasterId() == 0) {
                logged.setMasterId(logged.getDetailId());
            }
            map.clear();
            map.put("com.id <> " + logged.getMasterId(), " AND ");
            map.put("com.nombre = '" + getNombre(), "'  ");
            if (company_generalFind.byExist(map)) {
                throw new Exc("m5");
            }

            sql = "UPDATE public.compania SET "
                    + "nombre = '" + getNombre() + "',"
                    + "direccion= '" + getDireccion() + "',"
                    + "telefono= '" + getTelefono() + "',"
                    + "contacto = '" + getContacto() + "' "
                    + "WHERE id =" + logged.getMasterId();

            //Actualiza la información del registro
            persistencia.executeUpdate(sql);

            throw new Exc("m2");
        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void delete() {
        try {

            //Verifica si hay registros seleccionados
            if (logged.getMasterId() == 0) {
                throw new Exc("m4");
            }

            //Elimina el resgistro por el id_persona
            deleteById(logged.getMasterId());

            //logged.setTempId(0);
            clear();

            throw new Exc("m3");

        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
    }

    public void deleteById(int id) throws Exc, SQLException, Exception {
        //Verifica si el usuario ya existe para otra persona
        sql = "DELETE FROM public.compania "
                + "WHERE id = " + id;
        persistencia.executeUpdate(sql);
    }

    public void clear() {
        logged.setDetailId(0);
        clearBeans();
    }

    public void selectedTempId(int tempId) {
        logged.setDetailId(tempId);
        load();
    }

    private String namePackage() {
        Package pack = this.getClass().getPackage();
        return pack.getName();
    }

    public boolean acceso() {
        if (logged.getLoggedRol() == 1) {
            return false;
        }
        return true;

    }

    public boolean accesoRendered() {
        if (logged.getLoggedRol() == 1) {
            return true;
        }
        return false;

    }
}
